package de.zinulla.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class HttpHandler {

	public static final String OFDBGW_URL = "http://ofdbgw.home-of-root.de/";
	public static final String SEARCH_EAN = "searchean/";
	public static final String SEARCH_IMDB = "movie/";
	public static final String TEXT_HTML = "text/html";

	public static String getMovieTitelByEAN(String ean) {
		// Somewhere in your code this is called
		// ean = "4010884250886";
		String imdbID = "";
		String filmID = "";
		String movieName = "";
		String stream = "";
		StringBuilder builder = new StringBuilder();
		String urlFilmId = OFDBGW_URL + SEARCH_EAN + "/" + ean;
		String urlImdbId = OFDBGW_URL + SEARCH_IMDB + "/";
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGetFilmId = new HttpGet(urlFilmId);

		try {
			HttpResponse response = client.execute(httpGetFilmId);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();

			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				movieName = parseXMLMovieName(content);
				if (movieName.trim().length() > 1) {
					if (movieName.contains(" - ")) {
						movieName = movieName.substring(0, movieName.indexOf(" - "));
					}
				}
				// if (null != filmID && filmID.length() > 0) {
				// HttpGet httpGetImbdId = new HttpGet(urlImdbId + filmID);
				// HttpResponse response2 = client.execute(httpGetImbdId);
				// StatusLine statusLine2 = response2.getStatusLine();
				// int statusCode2 = statusLine2.getStatusCode();
				//
				// if (statusCode2 == 200) {
				// HttpEntity entity2 = response2.getEntity();
				// InputStream content2 = entity2.getContent();
				// imdbID = parseXMLImbdId(content2);
				// }
				// }
				// BufferedReader reader = new BufferedReader(new
				// InputStreamReader(content));
				// String line;
				// while ((line = reader.readLine()) != null) {
				// builder.append(line);
				// }
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return movieName;
	}

	// public static void getJSONMovieByID(String id) {
	// // Somewhere in your code this is called
	// String stream = "";
	// try {
	// URL url = new URL(OFDBGW_URL + SEARCH_MOVIE_BY_ID + "/" + id);
	// HttpURLConnection con = (HttpURLConnection) url.openConnection();
	// stream = readStream(con.getInputStream());
	//
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// try {
	// JSONArray jsonArray = new JSONArray(stream);
	// for (int i = 0; i < jsonArray.length(); i++) {
	// JSONObject jsonObject = jsonArray.getJSONObject(i);
	// String filmid = (String) jsonObject.get("filmid");
	// String titel = (String) jsonObject.get("titel");
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

	private static String parseXMLFilmId(InputStream xml) {
		String imdbID = "";
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		try {
			builder = builderFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		try {
			Document document = builder.parse(xml);
			Element rootElement = document.getDocumentElement();
			NodeList nodes = rootElement.getElementsByTagName("filmid");
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);

				if (node instanceof Element) {
					// a child element to process
					Node child = (Node) node.getFirstChild();
					imdbID = child.getNodeValue();
				}
			}

		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return imdbID;
	}

	private static String parseXMLMovieName(InputStream xml) {
		String movieName = "";
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		try {
			builder = builderFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		try {
			Document document = builder.parse(xml);
			Element rootElement = document.getDocumentElement();
			NodeList nodes = rootElement.getElementsByTagName("titel");
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);

				if (node instanceof Element) {
					// a child element to process
					Node child = (Node) node.getFirstChild();
					movieName = child.getNodeValue();
				}
			}

		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return movieName;
	}

	private static String parseXMLImbdId(InputStream xml) {
		String imdbID = "";
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		try {
			builder = builderFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		try {
			Document document = builder.parse(xml);
			Element rootElement = document.getDocumentElement();
			NodeList nodes = rootElement.getElementsByTagName("imdbid");
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);

				if (node instanceof Element) {
					// a child element to process
					Node child = (Node) node.getFirstChild();
					imdbID = child.getNodeValue();
				}
			}

		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return imdbID;
	}

	private static String readStream(InputStream in) {
		BufferedReader reader = null;
		StringBuilder builder = new StringBuilder();
		try {
			reader = new BufferedReader(new InputStreamReader(in));
			String line = "";
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return builder.toString();
	}
}
